// MonitorEventBus.ts - 监控系统专用事件总线
// @/utils/monitor/core/MonitorEventBus.ts

import { EventBus } from '../../eventBus';
import { MonitorEvent, EventType } from '../MonitorTypes';

/**
 * 监控事件总线
 * 基于企业级EventBus，为监控系统提供专门的事件处理
 */
export class MonitorEventBus {
  private eventBus: EventBus;
  private namespace: string = 'monitor';
  private isEnabled: boolean = true;
  private eventCounts: Map<string, number> = new Map();
  private enableDebug: boolean = false;

  constructor(debug: boolean = false) {
    this.eventBus = EventBus.getInstance();
    this.enableDebug = debug;
    this.setupMonitorSpecificHandlers();
  }

  /**
   * 设置监控系统专用的错误处理和调试
   */
  private setupMonitorSpecificHandlers(): void {
    // 设置监控专用错误处理器
    this.eventBus.setErrorHandler((error: Error, event: string) => {
      if (event.startsWith(this.namespace)) {
        if (this.enableDebug) {
          console.error(`[MonitorEventBus] Error in event "${event}":`, error);
        }
        // 可以在这里上报监控系统本身的错误
        this.trackInternalError(error, event);
      }
    });
  }

  /**
   * 监听监控事件
   */
  public on(eventType: EventType | string, handler: (data: any) => void): () => void {
    const eventName = this.getEventName(eventType);
    
    if (this.enableDebug) {
      console.log(`[MonitorEventBus] Registering handler for: ${eventName}`);
    }

    return this.eventBus.on(eventName, handler, { priority: 1 });
  }

  /**
   * 监听一次性监控事件
   */
  public once(eventType: EventType | string, handler: (data: any) => void): () => void {
    const eventName = this.getEventName(eventType);
    return this.eventBus.once(eventName, handler);
  }

  /**
   * 触发监控事件
   */
  public emit(eventType: EventType | string, data: any): void {
    if (!this.isEnabled) {
      return;
    }

    const eventName = this.getEventName(eventType);
    
    // 统计事件数量
    this.trackEventCount(eventName);
    
    // 添加监控专用的元数据
    const enrichedData = this.enrichEventData(data, eventType);
    
    if (this.enableDebug) {
      console.log(`[MonitorEventBus] Emitting: ${eventName}`, enrichedData);
    }

    // 使用异步emit确保不阻塞主线程
    this.eventBus.emit(eventName, enrichedData);
  }

  /**
   * 同步触发监控事件 (用于关键事件)
   */
  public emitSync(eventType: EventType | string, data: any): void {
    if (!this.isEnabled) {
      return;
    }

    const eventName = this.getEventName(eventType);
    const enrichedData = this.enrichEventData(data, eventType);
    
    this.trackEventCount(eventName);
    
    if (this.enableDebug) {
      console.log(`[MonitorEventBus] Emitting sync: ${eventName}`, enrichedData);
    }

    this.eventBus.emitSync(eventName, enrichedData);
  }

  /**
   * 批量触发事件 (性能优化)
   */
  public emitBatch(events: Array<{ type: EventType | string, data: any }>): void {
    if (!this.isEnabled || events.length === 0) {
      return;
    }

    // 使用微任务批量处理，避免阻塞
    Promise.resolve().then(() => {
      events.forEach(event => {
        this.emit(event.type, event.data);
      });
    });
  }

  /**
   * 取消监听
   */
  public off(eventType: EventType | string, handler?: (data: any) => void): void {
    const eventName = this.getEventName(eventType);
    this.eventBus.off(eventName, handler);
  }

  /**
   * 等待特定监控事件
   */
  public async waitFor(eventType: EventType | string, timeout: number = 5000): Promise<any> {
    const eventName = this.getEventName(eventType);
    return this.eventBus.waitFor(eventName, timeout);
  }

  /**
   * 启用/禁用事件总线
   */
  public setEnabled(enabled: boolean): void {
    this.isEnabled = enabled;
    if (this.enableDebug) {
      console.log(`[MonitorEventBus] ${enabled ? 'Enabled' : 'Disabled'}`);
    }
  }

  /**
   * 设置调试模式
   */
  public setDebug(debug: boolean): void {
    this.enableDebug = debug;
  }

  /**
   * 获取事件统计信息
   */
  public getEventStats(): Record<string, number> {
    const stats: Record<string, number> = {};
    this.eventCounts.forEach((count, event) => {
      stats[event] = count;
    });
    return stats;
  }

  /**
   * 重置事件统计
   */
  public resetStats(): void {
    this.eventCounts.clear();
  }

  /**
   * 获取监听器数量
   */
  public getListenerCount(eventType: EventType | string): number {
    const eventName = this.getEventName(eventType);
    return this.eventBus.listenerCount(eventName);
  }

  /**
   * 清理所有监控事件监听器
   */
  public clear(): void {
    // 只清理监控命名空间的事件
    const eventNames = this.eventBus.eventNames();
    eventNames.forEach(name => {
      if (name.startsWith(`${this.namespace}:`)) {
        this.eventBus.removeAllListeners(name);
      }
    });
    this.eventCounts.clear();
  }

  /**
   * 销毁事件总线
   */
  public destroy(): void {
    this.clear();
    this.isEnabled = false;
  }

  // ========== 私有方法 ==========

  /**
   * 生成带命名空间的事件名
   */
  private getEventName(eventType: EventType | string): string {
    return `${this.namespace}:${eventType}`;
  }

  /**
   * 丰富事件数据
   */
  private enrichEventData(data: any, eventType: EventType | string): any {
    return {
      ...data,
      _meta: {
        eventType,
        timestamp: Date.now(),
        namespace: this.namespace
      }
    };
  }

  /**
   * 统计事件数量
   */
  private trackEventCount(eventName: string): void {
    const currentCount = this.eventCounts.get(eventName) || 0;
    this.eventCounts.set(eventName, currentCount + 1);
  }

  /**
   * 追踪内部错误
   */
  private trackInternalError(error: Error, event: string): void {
    // 可以在这里实现监控系统自身的错误上报
    if (this.enableDebug) {
      console.error('[MonitorEventBus] Internal error:', {
        error: error.message,
        stack: error.stack,
        event,
        timestamp: Date.now()
      });
    }
  }
}

/**
 * 监控事件总线单例
 */
let monitorEventBusInstance: MonitorEventBus | null = null;

export function getMonitorEventBus(debug: boolean = false): MonitorEventBus {
  if (!monitorEventBusInstance) {
    monitorEventBusInstance = new MonitorEventBus(debug);
  }
  return monitorEventBusInstance;
}

/**
 * 销毁监控事件总线单例
 */
export function destroyMonitorEventBus(): void {
  if (monitorEventBusInstance) {
    monitorEventBusInstance.destroy();
    monitorEventBusInstance = null;
  }
} 